package pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lyx
 * @Date 2021/6/22 18:17
 */
public class JUCPCTest {
    public static void main(String[] args) {
            Data1 data = new Data1();

            new Thread(()->{
                for (int i = 0; i < 5; i++) {
                    try {
                        data.increment();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },"A").start();

            new Thread(()->{
                for (int i = 0; i < 5; i++) {
                    try {
                        data.decrement();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },"B").start();

            new Thread(()->{
                for (int i = 0; i < 5; i++) {
                    try {
                        data.increment();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },"C").start();


            new Thread(()->{
                for (int i = 0; i < 10; i++) {
                    try {
                        data.decrement();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },"D").start();


    }


}

//等待，业务，通知
class Data1{
    private int number = 0;
    Lock lock = new ReentrantLock();
    Condition condition =lock.newCondition();
    public synchronized void increment() throws InterruptedException {

        while (number!=0){//1的时候等待,为了防止假唤醒，我们要用while循环
            //等待
          condition.await();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"-->"+number);
        //唤醒，通知其他线程，我++完毕
        condition.signalAll();

    }

    public synchronized void decrement() throws InterruptedException {
        while (number==0){//0的时候等待
            condition.await();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"-->"+number);
        condition.signalAll();
    }

}